<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Otto WS control</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="./lib/picnic/picnic.min.css">
    <script type="text/javascript">

        // move constants
        const HOME = 0;
        const FORWARD = 1;
        const BACKWARD = 2;
        const LEFT_TURN = 3;
        const RIGHT_TURN = 4;

        const wsPort = 8181;
        let output;
        let websocket;

        let speed = 1000;
        let size  = 15;

        let batteryTimer;

        function init()
        {
            output = document.getElementById("output");
            testWebSocket();
        }

        function testWebSocket()
        {
            websocket = new WebSocket(((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host + ":" + wsPort + "/");
            websocket.onopen = function(evt) { onOpen(evt) };
            websocket.onclose = function(evt) { onClose(evt) };
            websocket.onmessage = function(evt) { onMessage(evt) };
            websocket.onerror = function(evt) { onError(evt) };
        }

        function onOpen(evt)
        {
            document.getElementById("connStat").classList.remove('tryConnDot');
            document.getElementById("connStat").classList.remove('disConnDot');
            document.getElementById("connStat").classList.add('connDot');
            writeToScreen("CONNECTED");
            sendMove([HOME]);
            // call for battery info
            getBatteryInfo();
            // setup to call batteryInfo every 30 seconds
            batteryTimer = setInterval(getBatteryInfo, 30000);
        }

        function onClose(evt)
        {
            document.getElementById("connStat").classList.remove('connDot');
            document.getElementById("connStat").classList.remove('tryConnDot');
            document.getElementById("connStat").classList.add('disConnDot');
            clearInterval(batteryTimer);
            writeToScreen("DISCONNECTED");
        }

        function onMessage(evt)
        {
            // look to see if this is info we want
            let response = JSON.parse(evt.data);

            if (response.type === "ottoResponse")
            {
                // there are a few, for now battery is all I want

                if (response.command === "B")
                {
                    // update the battery
                    updateBatteryDisplay(response.result);
                }
            }
            else if (response.type === "ottoAck") {
                writeToScreen('<span style="color: blue;">ACK: ' + response.command + '</span>');
            }
            else if (response.type === "ottoFinalAck") {
                writeToScreen('<span style="color: green;">FINAL_ACK: ' + response.command + '</span>');
            }
       }

        function onError(evt)
        {
            writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
        }

        function sendMove(move)
        {
            let cmd = ['M'];

            for (let i = 0; i < move.length ; i++)
                cmd.push(move[i].toString())

            let msg = {
                type: "ottoCommand",
                command: cmd,
            };

            writeToScreen("SENT: " + JSON.stringify(msg));
            websocket.send(JSON.stringify(msg) + "\n");

            if (move[0] !== HOME)
            {
                // if this wasn't a home move, then send home as well
                sendMove([HOME]);
            }
        }

        function sendSong(song)
        {
            let cmd = ['K'];

            for (let i = 0; i < song.length ; i++)
                cmd.push(song[i].toString())

            let msg = {
                type: "ottoCommand",
                command: cmd,
            };

            writeToScreen("SENT: " + JSON.stringify(msg));
            websocket.send(JSON.stringify(msg) + "\n");
        }

        function sendGesture(gesture)
        {
            let cmd = ['H'];

            for (let i = 0; i < gesture.length ; i++)
                cmd.push(gesture[i].toString())

            let msg = {
                type: "ottoCommand",
                command: cmd,
            };

            writeToScreen("SENT: " + JSON.stringify(msg));
            websocket.send(JSON.stringify(msg) + "\n");
        }

        function sendMouth(mouth)
        {
            let cmd = ['L'];

            let binStr = mouth[0].toString(2);
            let len = binStr.length;
            let pre = '0'.repeat(31-len);
            cmd.push(pre + binStr);

            let msg = {
                type: "ottoCommand",
                command: cmd,
            };

            writeToScreen("SENT: " + JSON.stringify(msg));
            websocket.send(JSON.stringify(msg) + "\n");
        }

        function getBatteryInfo()
        {
            // create the command to get the battery info from Otto
            let msg = {
                type: "ottoCommand",
                command: ["B"]
            }

            writeToScreen("SENT: " + JSON.stringify(msg));
            websocket.send(JSON.stringify(msg) + "\n");
        }

        function doSend(message)
        {
            msg = {
                type: "ottoCommand",
                cmmand: ['M', '0'],
            };

            writeToScreen("SENT: " + JSON.stringify(msg));
            websocket.send(JSON.stringify(msg) + "\n");
            msg.command = ['L', '0000000100001010010001100000000'];
            websocket.send(JSON.stringify(msg) + "\n");
        }

        function writeToScreen(message)
        {
            let pre = document.createElement("p");
            pre.style.wordWrap = "break-word";
            pre.innerHTML = message;
            output.appendChild(pre);
        }

        function getSpeed()
        {
            let radios = document.getElementsByName('speed');

            for (let i = 0, length = radios.length; i < length; i++) {
                if (radios[i].checked) {
                    // do whatever you want with the checked radio
                    return parseInt(radios[i].value);
                }
            }
        }

        function updateBatteryDisplay(level) {
            var batteryLevel = document.getElementById("battery-level");
            if (level < 2)
                batteryLevel.style.width = 2 + '%';
            else
                batteryLevel.style.width = level + '%';
            batteryLevel.innerText = level + '%';
            if (level > 50) {
                batteryLevel.classList.add('high');
                batteryLevel.classList.remove('medium');
                batteryLevel.classList.remove('low');
            } else if (level >= 25 ) {
                batteryLevel.classList.add('medium');
                batteryLevel.classList.remove('high');
                batteryLevel.classList.remove('low');
            } else {
                batteryLevel.classList.add('low');
                batteryLevel.classList.remove('high');
                batteryLevel.classList.remove('medium');
            }
        }

        function showIFrame(evt, frameUrl) {
            // Declare all variables
            var i, tablinks;

            // Get all elements with class="tablinks" and remove the class "active"
            tablinks = document.getElementsByClassName("tabLink");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace(" active", "");
            }

            // Show the current tab, and add an "active" class to the button that opened the tab
            document.getElementById("buttonIFrame").src = frameUrl;
            evt.currentTarget.className += " active";
        }

        window.addEventListener("load", init, false);

    </script>

    <style>
        body {
            background-color: #eeeeee;
        }
        .myPict {
            line-height: 0em;
            padding-bottom: 0em;
            text-align: center;
        }
        @media screen and (max-width: 1000px){
            .myImg {
                width: 55px;
                height: 55px;
            }
            .buttonIFrame {
                height: 205px;
            }
        }
        @media screen and (min-width: 1000px){
            .myImg {
                width: 110px;
                height: 110px;
            }
            .buttonIFrame {
                height: 380px;
            }
        }
        @media screen and (min-width: 1500px){
            .myImg {
                width: 165px;
                height: 165px;
            }
            .buttonIFrame {
                height: 550px;
            }
        }
        .myImg {
            line-height: 0em;
            padding-bottom: 0em;
            text-align: center;
            background-color: #0074d9;
            border: 5px solid #111111;
        }
        .buttonIFrame {
            width: 100%;
            border: 0;
        }
        .thinBorder {
            border: 2px solid #2ecc40;
        }
        .clearButton {
            background-color: inherit;
        }
        .tabContent {
            display: none;
        }
        .battery:after {
            background-color: #fff;
            border: 2px solid #000;
            content: "";
            display: block;
            height: 16px;
            position: absolute;
            right: -6px;
            top: 4px;
            width: 6px;
        }
        .battery {
            background-color: #fff;
            border: 2px solid #000;
            height: 32px;
            margin-left: auto;
            margin-right: auto;
            position: relative;
            width: 100px;
        }
        .battery .battery-level {
            background-color: #666;
            height: 100%;
            text-align: center;
        }
        .battery .battery-level.high {
            background-color: #66CD00;
        }
        .battery .battery-level.medium {
            background-color: #FCD116;
        }
        .battery .battery-level.low {
            background-color: #FF3333;
        }
        .disConnDot {
            height: 25px;
            width: 25px;
            background-color: #ff4136;
            border-radius: 50%;
            display: inline-block;
        }
        .connDot {
            height: 25px;
            width: 25px;
            background-color: #2ecc40;
            border-radius: 50%;
            display: inline-block;
        }
        .tryConnDot {
            height: 25px;
            width: 25px;
            background-color: #ff851b;
            border-radius: 50%;
            display: inline-block;
        }
    </style>
</head>
<body>
<h2 align="center">Otto remote control</h2>
<div class="flex three">
    <div align="center">
        Conn <span id="connStat" class="tryConnDot"></span>
    </div>
    <div class="off-third">
        <div class="battery" id="battery">
            <div id="battery-level" class="battery-level">??</div>
        </div>
    </div>
</div>
<div class="flex three">
    <div id="spd" class="off-third">
        <label>
            <input type="radio" id="slow" name="speed" value="1500">
            <span class="checkable">Slow</span>
        </label><br>
        <input type="radio" id="normal" name="speed" value="1000" checked="checked">
        <label for="normal" class="checkable">Normal</label><br>
        <input type="radio" id="fast" name="speed" value="500">
        <label for="fast" class="checkable">Fast</label>
    </div>
</div>
<div class="flex three">
    <div id="control" class="off-sixth two-third off-third-500 third-500">
        <div class="flex three">
            <div data-tooltip="Move Forward" class="myPict off-third tooltip-top" onclick="sendMove([FORWARD, getSpeed()])">
                <img class="myImg" src="images/Control/forward@2x.png" alt="Forward">
            </div>
        </div>
        <div class="flex three">
            <div data-tooltip="Turn Left" class="myPict tooltip-top" onclick="sendMove([LEFT_TURN, getSpeed()])">
                <img class="myImg" src="images/Control/left@2x.png" alt="Left">
            </div>
            <div data-tooltip="Turn Right" class="off-third myPict tooltip-top" onclick="sendMove([RIGHT_TURN, getSpeed()])">
                <img class="myImg" src="images/Control/right@2x.png" alt="Right">
            </div>
        </div>
        <div class="flex three">
            <div data-tooltip="Move Backward" class="off-third tooltip-top myPict" onclick="sendMove([BACKWARD, getSpeed()])">
                <img class="myImg" src="images/Control/backward@2x.png" alt="Backward">
            </div>
        </div>
    </div>
</div>

<iframe id="buttonIFrame" class="buttonIFrame" scrolling="no" src="moves.html" title="buttons"></iframe>

<div class="flex six">
    <div class="off-sixth two-third thinBorder">
        <div class="flex four">
            <button id="defaultTab" class="clearButton tabLink" onclick="showIFrame(event, 'moves.html')">
                <div data-tooltip="Moves" >
                    <img class="myImg" src="images/Buttons/Swing/swing@2x.png"/>
                </div>
            </button>
            <button class="clearButton tabLink" onclick="showIFrame(event, 'songs.html')">
                <div data-tooltip="Songs">
                    <img class="myImg" src="images/Buttons/Humanoid/Beep/beep@2x.png"/>
                </div>
            </button>
            <button class="clearButton tabLink" onclick="showIFrame(event, 'gestures.html')">
                <div data-tooltip="Gestures">
                    <img class="myImg" src="images/Buttons/Gestures/SuperHappy/superhappy@2x.png"/>
                </div>
            </button>
            <button class="clearButton tabLink" onclick="showIFrame(event, 'mouths.html')">
                <div data-tooltip="Mouths">
                    <img class="myImg" src="images/Buttons/Humanoid/Mouth/SuperHappy/superhappy@2x.png"/>
                </div>
            </button>
        </div>
    </div>
</div>

<div class="flex twelve">
    <div id="output" class="off-sixth four-fifth card center">output</div>
</div>

</body>
</html>